package com.zxf.appliction.util;

import java.util.*;

/**
 * Created by YangBQ on 2017/4/21.
 */
public class PropertiesFileUtils {

    /**
     * 当打开多个资源文件时，缓存资源文件map
     */
    private static Map<String, PropertiesFileUtils> configMap = new HashMap<>();
    /**
     * 缓存文件时间（打开问价时间）
     */
    private Date loadTime = null;
    /**
     * 资源文件
     */
    private ResourceBundle resourceBundle = null;

    /**
     * 默认资源文件名
     */
    private static final String CONFIG_NAME = "application";
    /**
     * 缓存有效期，一分钟
     */
    private static final Integer TIME_OUT = 60 * 1000;

    /**
     * 私有化构造方法，创建单实例
     * @param name
     */
    private PropertiesFileUtils(String name) {
        this.loadTime = new Date();
        this.resourceBundle = ResourceBundle.getBundle(name);
    }

    public static synchronized PropertiesFileUtils getInstance() {
        return getInstance(CONFIG_NAME);
    }

    public static PropertiesFileUtils getInstance(String configName) {
        PropertiesFileUtils config = configMap.get(configName);
        if (null == config) {
            config = new PropertiesFileUtils(configName);
            configMap.put(configName, config);
        }
        /**
         * 缓存失效，重新读取配置文件，加入缓存
         */
        if ((new Date().getTime() - config.getLoadTime().getTime()) > TIME_OUT) {
            config = new PropertiesFileUtils(configName);
            configMap.put(configName, config);
        }
        return config;
    }

    /**
     * 根据key读取资源文件的value
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            String value = resourceBundle.getString(key);
            return value;
        } catch (MissingResourceException e) {
            return "";
        }
    }

    /**
     * 读取integer类型的值
     * @param key
     * @return
     */
    public Integer getInt(String key) {
        try {
            String value = resourceBundle.getString(key);
            return Integer.parseInt(value);
        } catch (MissingResourceException e) {
            return null;
        }
    }

    /**
     * 读取Boolean类型的值
     * @param key
     * @return
     */
    public boolean getBoolean(String key) {
        try {
            String value = resourceBundle.getString(key);
            if ("true".equals(value)) {
                return true;
            }
            return false;
        } catch (MissingResourceException e) {
            return false;
        }
    }

    public Date getLoadTime() {
        return loadTime;
    }




}
